package com.yjr.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yjr.gulimall.product.service.CategoryBrandRelationService;
import com.yjr.gulimall.product.vo.Catalog3Vo;
import com.yjr.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjr.common.utils.PageUtils;
import com.yjr.common.utils.Query;

import com.yjr.gulimall.product.dao.CategoryDao;
import com.yjr.gulimall.product.entity.CategoryEntity;
import com.yjr.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

   @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
   @Autowired
    RedissonClient redissonClient;

   @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        return categoryEntityList;
    }

    @Override
    public void removeMeunByIds(List<Long> asList) {

        //TODD
        // 删除之前需要判断待删除的菜单那是否被别的地方所引用。
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCateLogPath(Long catelogId) {
        //根据三级分类ID查找分类路径
        List<Long> pathList=new ArrayList<>();
        pathList = findParentPath(catelogId, pathList);
        Collections.reverse(pathList);
        return  pathList.toArray(new Long[pathList.size()]);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    //@CacheEvict(value = {"catagory"}, key="'getLevel1Categorys'")
    @Caching(evict = {
            @CacheEvict(value = {"catagory"}, key = "'getLevel1Categorys'"),
            @CacheEvict(value = {"catagory"}, key = "'getCatelogJsonFromDBWithRedissonLock'")})
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    @Override
    //@Cacheable(value = {"category"},key = "'Level1Categorys'")
    //sync = true解决缓存击穿
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    public List<CategoryEntity> getLevel1Categorys() {

       return this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));

    }

    //分布式锁(原生版)
    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDBWithRedisLock(){
        String uuid= UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if(lock){
            // 2.设置过期时间加锁成功 获取数据释放锁 [分布式下必须是Lua脚本删锁,不然会因为业务处理时间、网络延迟等等引起数据还没返回锁过期或者返回的过程中过期 然后把别人的锁删了]
            Map<String, List<Catelog2Vo>> data;

            try {
                //执行业务
                data=getCatlogJson();
            } finally {
                String lockValue = stringRedisTemplate.opsForValue().get("lock");

                // 删除也必须是原子操作 Lua脚本操作 删除成功返回1 否则返回0
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

                //原子删锁
                stringRedisTemplate.execute(new DefaultRedisScript<>(script,Long.class),Arrays.asList("lock"),uuid);
            }

            return  data;
        }
        else {
            // 重试加锁
            try {
                // 登上两百毫秒
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //重试加锁
        return  getCatelogJsonFromDBWithRedisLock();

    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name")
    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDBWithRedissonLock() {

        //使用分布式锁
        RLock lock = redissonClient.getLock("CatelogJson-lock");
        lock.lock();
        log.info("锁上了...."+Thread.currentThread().getId());
        Map<String, List<Catelog2Vo>> data;
        try {

            data=getCatlogJson();
        }
        finally {
            lock.unlock();
            log.info("解锁了...."+Thread.currentThread().getId());
        }

        return  data;
    }

    public Map<String, List<Catelog2Vo>> getCatlogJson() {
        //synchronized (this) {
//            String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
//            if (StringUtils.isNotEmpty(catalogJSON)) {
//
//                return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
//                });
//            }
            Map<String, List<Catelog2Vo>> catlogJsonFromDB = getCatlogJsonFromDB();
            String toJSONString = JSON.toJSONString(catlogJsonFromDB);
            stringRedisTemplate.opsForValue().set("catalogJSON", toJSONString);
            return catlogJsonFromDB;
        //}
    }

    public Map<String, List<Catelog2Vo>> getCatlogJsonFromDB() {
        log.info("进来查询数据库了");
        List<CategoryEntity> categoryEntityList = this.list(); //查询出全部的分类集合
        if(!CollectionUtils.isEmpty(categoryEntityList)){
            //查询出一级分类
            List<CategoryEntity> categoryEntityListLevel1 = getCategoryEntities(categoryEntityList, 0L);
            Map<String, List<Catelog2Vo>> collect = categoryEntityListLevel1.stream().collect(Collectors.toMap(categoryEntity -> categoryEntity.getCatId().toString(), v -> {
                List<Catelog2Vo> catelog2Vos = new ArrayList<>();
                List<CategoryEntity> categoryEntitiesLevel2 = getCategoryEntities(categoryEntityList, v.getCatId());
                if (!CollectionUtils.isEmpty(categoryEntitiesLevel2)) {
                    catelog2Vos = categoryEntitiesLevel2.stream().map(categoryEntity -> {

                        Catelog2Vo catelog2Vo = new Catelog2Vo(categoryEntity.getCatId().toString(), categoryEntity.getName(), categoryEntity.getParentCid().toString(), null);
                        List<CategoryEntity> categoryEntitiesLevel3 = getCategoryEntities(categoryEntityList, categoryEntity.getCatId());
                        if (!CollectionUtils.isEmpty(categoryEntitiesLevel3)) {
                            List<Catalog3Vo> catalog3Vos = categoryEntitiesLevel3.stream().map(categoryEntity3 -> new Catalog3Vo(categoryEntity3.getCatId().toString(), categoryEntity3.getName(), categoryEntity3.getParentCid().toString())).collect(Collectors.toList());
                            if (!CollectionUtils.isEmpty(catalog3Vos)) {
                                catelog2Vo.setCatalog3List(catalog3Vos);
                            }
                        }

                        return catelog2Vo;
                    }).collect(Collectors.toList());
                }

                return catelog2Vos;
            }));

            return  collect;
        }

        return null;
    }

    public  List<Long> findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity category = this.getById(catelogId); //查询出当前分类
        if(category.getParentCid()!=0){

            findParentPath(category.getParentCid(),paths);
        }
        return paths;
    }

    private List<CategoryEntity> getCategoryEntities(List<CategoryEntity> entities,Long parentId){

        return entities.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(parentId)).collect(Collectors.toList());
    }

}